package com.codestudy.controller;

import cn.undraw.util.result.R;
import com.codestudy.common.LoginUtil;
import com.codestudy.dto.CommentDTO;
import com.codestudy.entity.Comment;
import com.codestudy.service.CommentLikeService;
import com.codestudy.service.CommentService;
import com.codestudy.service.NoteService;
import com.codestudy.vo.CommentVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@RestController
@CrossOrigin
@Api(tags = "评论管理")
@RequestMapping("/comment")
public class CommentController {
    @Resource
    NoteService noteService;
    @Resource
    private CommentService commentService;
    @Resource
    private CommentLikeService commentLikeService;

    @ApiOperation("添加评论")
    @PostMapping("/save")
    public R<?> save(@RequestBody CommentDTO commentDTO) {
        return R.ok(commentService._save(commentDTO));
    }

    @ApiOperation("删除评论")
    @DeleteMapping("/remove/{id}")
    public R remove(@PathVariable Integer id) {
        Comment comment = new Comment();
        comment.setId(id);
        Integer uid = commentService.selectUid(id);
        /*判断删除评论的用户id与评论的uid是否一致*/
        if (Objects.equals(uid, LoginUtil.getCurrentId())) {
            boolean removeById = commentService.removeById(id);
            if (removeById) {
                return R.ok("删除成功！");
            }
        }

        /*判断用户id是否是发布文章的用户*/
        //比较noteId.userId=LoginUtil.getCurrentId()
        //1.拿到noteId的userId
        Integer noteId = commentService.selectArticle(id);
        Integer userId = noteService.findNoteByUserId(noteId);
        //2.比较
        if (Objects.equals(userId, LoginUtil.getCurrentId())) {
            boolean removeById = commentService.removeById(id);
            if (removeById) {
                return R.ok("删除成功！");
            }
        }
        return R.fail("删除失败！您不是评论发布者");
    }

    @ApiOperation("评论点赞")
    @PostMapping("/liked/{commentId}")
    public R liked(@PathVariable Integer commentId) {
//        LikedDTO.set(LoginUtil.getCurrentId());
        R doComment = commentLikeService.liked(commentId);
        return R.ok(doComment);
    }

    @GetMapping("/commentSelect")
    @ApiOperation(value = "查询评论列表", notes = "query传参")
    public R commentSelect(Integer noteId) {
        log.info("查询评论文章ID为：{}", noteId);
        List<CommentVO> commentVOList = commentService.commentSelect(noteId);
        return R.ok(commentVOList);
    }

    @ApiOperation("查询当前用户的点赞过的评论id")
    @GetMapping("/cidList/{uid}")
    public R cidList(@PathVariable Integer uid) {
        return commentLikeService.cidListByUid(uid);
    }

}
